package com.gitee.deament.server.core.hander;

import com.gitee.deament.server.core.cli.CliHandler;
import com.gitee.deament.server.core.data.ConnectData;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author deament
 */
public class CommandHander extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

        //下一个处理链

        //channelHandlerContext.fireChannelActive();
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
        logger.info("handlerRemoved" + ctx.channel().id().asLongText());
        ConnectData.userQuitEvent( ctx.channel().id().asLongText());


    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
        logger.info("handlerAdded" + ctx.channel().id().asLongText());
        ConnectData.userAddEvent( ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("异常{}", cause);
    }


    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        if(msg instanceof TextWebSocketFrame){
            TextWebSocketFrame content = (TextWebSocketFrame)msg;
            CliHandler cliContext= new CliHandler();
            logger.info("command:"+content.text());

            cliContext.dealCli(channelHandlerContext,content.text());
            return ;
        }
        if(msg instanceof DefaultFullHttpRequest){
         DefaultFullHttpRequest req = (DefaultFullHttpRequest)msg;
//
//            logger.info("DefaultFullHttpRequest ");

//            logger.info("isReadable="+req.content().isReadable());
//            channelHandlerContext.writeAndFlush(req);
          ;

            channelHandlerContext.writeAndFlush("+OK".getBytes());

        }
        logger.info("anthor");
        //channelHandlerContext.writeAndFlush(new TextWebSocketFrame("\"OK\""));
//         ReferenceCountUtil.release(msg);
    }
}
